package scau.zhong.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import scau.zhong.common.user.auth.JwtUtils;
import scau.zhong.common.user.auth.Payload;
import scau.zhong.config.RsaKeyProperties;
import scau.zhong.pojo.User;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户认证校验
 */
public class JwtVerifyFilter extends BasicAuthenticationFilter {

    private RsaKeyProperties rsaKeyProperties;
    public JwtVerifyFilter(AuthenticationManager authenticationManager,RsaKeyProperties rsaKeyProperties) {
        super(authenticationManager);
        this.rsaKeyProperties = rsaKeyProperties;
    }

    /**
     * 验证用户
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String header = request.getHeader("Authorization");
        if (header == null ||  !header.startsWith("Zhong ")) {
            //未携带错误的token，提示用户登录
            chain.doFilter(request, response);
            response.setContentType("application/json;charset=utf-8");
            response.setStatus(HttpServletResponse.SC_FORBIDDEN); //403异常
            try {
                PrintWriter writer = response.getWriter();
                Map resultMap = new HashMap();
                resultMap.put("code",HttpServletResponse.SC_FORBIDDEN);
                resultMap.put("msg","未登录，请先登录:)");
                writer.write(new ObjectMapper().writeValueAsString(resultMap));
                writer.flush();
                writer.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        } else {
            //获取当前用户信息
            String token = header.replace("Zhong ", "");
            //验证token
            Payload<User> infoFromToken = JwtUtils.getInfoFromToken(token, rsaKeyProperties.getPublicKey(), User.class);
            User user = infoFromToken.getUserInfo();
            if(user!=null){
                UsernamePasswordAuthenticationToken authResult = new UsernamePasswordAuthenticationToken(user.getUsername(),null,user.getRoles());
                SecurityContextHolder.getContext().setAuthentication(authResult);
                chain.doFilter(request, response);
            }
        }
    }

    private void printResult(HttpServletResponse response,int code,String msg) {
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(code); //403异常
        try {
            PrintWriter writer = response.getWriter();
            Map resultMap = new HashMap();
            resultMap.put("code",code);
            resultMap.put("msg",msg);
            writer.write(new ObjectMapper().writeValueAsString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
